package com.scholarone.s1exporttool.web;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.scholarone.s1exporttool.domain.Resource;
import com.scholarone.s1exporttool.service.ExportService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	private ExportService exportService;
	
	@ModelAttribute("serverTime")
	protected String putDate(Locale locale){
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);		
		String formattedDate = dateFormat.format(date);
		//model.addAttribute("serverTime", formattedDate );		
		return formattedDate;
	}
	
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! the client locale is "+ locale.toString());				
		List<Resource> resourceList = exportService.getResources();		
		model.addAttribute("resources", resourceList);				
		return "home";
	}
	
	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public String handleFormUpload(@RequestParam("datasource") Integer dataSourceId, 
	    @RequestParam("file") MultipartFile file) {
		try{
			
		    if (!file.isEmpty()) {
		        //byte[] bytes = file.getBytes();
		        // store the bytes somewhere
		    	exportService.importXML(dataSourceId, file.getInputStream());
		   } 
	    }catch (Exception e) {
			// TODO: handle exception
		}
    	return "home";
	}	
	
}
